using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace MouseKeyboardOperationSimulator
{
    public partial class MouseKeyboardOperationSimulator : Form
    {
        
        // 主题管理器
        private ThemeManager themeManager;
        
        // 添加变量来记录最后获得焦点的单元格行和列
        private int lastFocusedRow = -1;
        private int lastFocusedColumn = -1;
        
        // 鼠标坐标采集相关变量
        private bool isCapturingMousePosition = false;
        private bool dontShowMouseCaptureDialog = false;

        
        // 键盘输入捕获相关变量
        private bool isCapturingKeyboardInput = false;
        private List<string> capturedKeys = new List<string>();
        
        // 程序运行状态标志
        private bool isProgramRunning = false;
        
        // 键盘钩子管理器
        private KeyboardHookManager keyboardHookManager;
        
        // DataGridView管理器
        private DataGridViewManager dataGridViewManager;
        
        // 错误行记录列表
        private List<int> errorRows = new List<int>();

        // 当前执行行高亮显示方法
        private void HighlightRow(int rowIndex)
        {
            if (rowIndex >= 0 && rowIndex < dataGridViewOperationList.Rows.Count)
            {
                // 取消之前选中的行
                foreach (DataGridViewRow row in dataGridViewOperationList.Rows)
                {
                    row.Selected = false;
                }
                
                // 选中当前行
                dataGridViewOperationList.Rows[rowIndex].Selected = true;
                
                // 确保当前行可见
                dataGridViewOperationList.FirstDisplayedScrollingRowIndex = rowIndex;
                
                // 刷新界面
                dataGridViewOperationList.Refresh();
            }
        }

        // 开始执行的快捷键
        private string startHotKey = "F6";

        // 退出执行的快捷键
        private string exitHotKey = "Escape";

        // 窗体构造函数中初始化默认退出快捷键
        public MouseKeyboardOperationSimulator()
        {
            InitializeComponent();

            // 初始化主题管理器并应用主题
            themeManager = new ThemeManager();
            themeManager.ApplyTheme(this);

            // 初始化键盘钩子管理器
            keyboardHookManager = new KeyboardHookManager();
            keyboardHookManager.StartHook();
            
            // 订阅键盘事件
            keyboardHookManager.KeyPressed += KeyboardHookManager_KeyPressed;
            
            // 初始化DataGridView管理器
            dataGridViewManager = new DataGridViewManager(dataGridViewOperationList, themeManager);
            
            // 订阅DataGridView事件到DataGridViewManager
            dataGridViewOperationList.CellValueChanged += dataGridViewManager.DataGridView_CellValueChanged;
            dataGridViewOperationList.EditingControlShowing += dataGridViewManager.DataGridView_EditingControlShowing;
            dataGridViewOperationList.CellClick += dataGridViewManager.DataGridView_CellClick;
            dataGridViewOperationList.DataError += dataGridViewManager.DataGridView_DataError;
            dataGridViewOperationList.UserAddedRow += dataGridViewManager.DataGridView_UserAddedRow;
            dataGridViewOperationList.UserDeletedRow += dataGridViewManager.DataGridView_UserDeletedRow;
            dataGridViewOperationList.CellMouseEnter += dataGridViewManager.DataGridView_CellMouseEnter;
            dataGridViewOperationList.CellMouseLeave += dataGridViewManager.DataGridView_CellMouseLeave;
            dataGridViewOperationList.CurrentCellDirtyStateChanged += dataGridViewManager.DataGridView_CurrentCellDirtyStateChanged;
            
            // 订阅窗体Shown事件，用于设置第一行的选中状态
            this.Shown += MouseKeyboardOperationSimulator_Shown;

            UpdateTitleWithStartAndExitKey();
        }

        /// <summary>
        /// 重新加载并应用主题
        /// </summary>
        public void ReloadTheme()
        {
            themeManager.ReloadTheme();
            themeManager.ApplyTheme(this);
            
            // 重新应用DataGridView样式
            if (dataGridViewManager != null)
            {
                // 触发一次数据刷新以确保样式正确应用
                dataGridViewOperationList.Refresh();
            }
        }

        /// <summary>
        /// 切换主题
        /// </summary>
        /// <param name="themePath">主题文件路径</param>
        public void SwitchTheme(string themePath)
        {
            themeManager = new ThemeManager(themePath);
            themeManager.ApplyTheme(this);
            
            // 重新应用DataGridView样式
            if (dataGridViewManager != null)
            {
                // 触发一次数据刷新以确保样式正确应用
                dataGridViewOperationList.Refresh();
            }
        }

        // 窗体显示事件处理方法
        private void MouseKeyboardOperationSimulator_Shown(object sender, EventArgs e)
        {
            // 如果DataGridView中有行，则设置第一行选择列为选中状态
            if (dataGridViewOperationList.Rows.Count > 0)
            {
                // 获取CheckStatus列的索引
                int checkStatusColumnIndex = dataGridViewOperationList.Columns["CheckStatus"].Index;
                
                // 设置第一行选择列为选中状态
                if (checkStatusColumnIndex >= 0 && dataGridViewOperationList.Rows[0].Cells[checkStatusColumnIndex] != null)
                {
                    dataGridViewOperationList.Rows[0].Cells[checkStatusColumnIndex].Value = true;
                }
                
                // 设置第一行的行号
                var indexCell = dataGridViewOperationList.Rows[0].Cells["Index"];
                if (indexCell != null)
                {
                    indexCell.Value = "1";
                }
            }
        }

        // 停止程序执行
        private void StopProgramExecution()
        {
            // 设置程序运行状态为false
            isProgramRunning = false;
            
            labelRunStatus.Text = "准备执行";
            
            // 可以在这里添加其他停止执行的逻辑
            // 例如：停止计时器、重置界面等
            
            // 使用异步方式显示提示消息，避免阻塞UI线程
            Task.Run(() =>
            {
                // 在UI线程上显示消息框
                this.Invoke(new Action(() =>
                {
                    MessageBox.Show("程序执行已停止。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }));
            });
        }
        
        // 执行任务列表
        private void ExecuteTaskList()
        {
            // 获取选中的行
            List<DataGridViewRow> executeRows = GetExecuteRows();
            
            // 如果没有选中的行，提示用户
            // 但如果是由于验证失败导致的空列表，则不显示此提示
            if (executeRows.Count == 0)
            {
                // 检查是否是由于验证失败导致的空列表
                // 我们可以通过检查errorRows集合来判断
                if (errorRows.Count == 0)
                {
                    MessageBox.Show("没有选中的操作行，请至少选择一行进行执行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return;
            }
            
            // 设置程序运行状态为true
            isProgramRunning = true;
            
            labelRunStatus.Text = "正在执行";
            
            try
            {
                // 使用索引遍历选中的行并执行操作，支持循环控制
                for (int i = 0; i < executeRows.Count; i++)
                {
                    // 检查程序是否仍在运行状态
                    if (!isProgramRunning)
                    {
                        break;
                    }
                    
                    DataGridViewRow row = executeRows[i];
                    
                    // 高亮显示当前执行的行
                    HighlightRow(row.Index);
                    
                    // 获取设备类型、操作类型和操作内容
                    string deviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString();
                    string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                    string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString();
                    
                    // 处理循环操作
                    if (deviceType == "循环")
                    {
                        if (operationType == "开始")
                        {
                            // 查找循环结束位置
                            int loopEndIndex = FindLoopEndIndex(executeRows, i);
                            if (loopEndIndex != -1)
                            {
                                // 获取循环次数
                                int loopCount = -1; // -1 表示无限循环
                                if (!string.IsNullOrEmpty(operationContent) && 
                                    int.TryParse(operationContent.Trim(), out int count) && count > 0)
                                {
                                    loopCount = count;
                                }
                                
                                // 执行循环体（最外层循环，层级为1）
                                ExecuteLoop(executeRows, i + 1, loopEndIndex - 1, loopCount, 1);
                                
                                // 跳过循环体行
                                i = loopEndIndex;
                            }
                        }
                        // 循环结束操作不需要特殊处理
                        continue;
                    }
                    
                    // 根据设备类型和操作类型执行相应的操作
                    switch (deviceType)
                    {
                        case "鼠标":
                            ExecuteMouseOperation(operationType, operationContent);
                            break;
                        case "键盘":
                            ExecuteKeyboardOperation(operationType, operationContent);
                            break;
                        case "延时":
                            ExecuteDelayOperation(operationContent);
                            break;
                    }
                    
                    // 在执行完每步操作后再次检查程序是否仍在运行状态
                    if (!isProgramRunning)
                    {
                        break;
                    }
                }
                
                // 如果程序正常执行完成，重置状态
                if (isProgramRunning)
                {
                    isProgramRunning = false;
                    labelRunStatus.Text = "准备执行";
                    MessageBox.Show("所有操作已执行完成。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                // 发生异常时停止执行并显示错误信息
                isProgramRunning = false;
                labelRunStatus.Text = "准备执行";
                MessageBox.Show(string.Format("执行过程中发生错误：{0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        // 执行鼠标操作
        private void ExecuteMouseOperation(string operationType, string operationContent)
        {
            try
            {
                switch (operationType)
                {
                    case "移动到坐标":
                    case "左键单击":
                    case "左键双击":
                    case "右键单击":
                    case "右键双击":
                    case "中键单击":
                        // 解析坐标 (x,y)
                        if (!string.IsNullOrEmpty(operationContent) && operationContent.Contains(","))
                        {
                            string[] parts = operationContent.Split(',');
                            if (parts.Length == 2 && 
                                int.TryParse(parts[0].Trim(), out int x) && 
                                int.TryParse(parts[1].Trim(), out int y))
                            {
                                switch (operationType)
                                {
                                    case "移动到坐标":
                                        HelperFunctions.SetMousePosition(x, y);
                                        break;
                                    case "左键单击":
                                        HelperFunctions.MouseLeftClick(x, y);
                                        break;
                                    case "左键双击":
                                        HelperFunctions.MouseLeftDoubleClick(x, y);
                                        break;
                                    case "右键单击":
                                        HelperFunctions.MouseRightClick(x, y);
                                        break;
                                    case "右键双击":
                                        HelperFunctions.MouseRightDoubleClick(x, y);
                                        break;
                                    case "中键单击":
                                        HelperFunctions.MouseMiddleClick(x, y);
                                        break;
                                }
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("无效的坐标格式: {0}", operationContent));
                            }
                        }
                        else
                        {
                            throw new ArgumentException(string.Format("坐标不能为空或格式不正确: {0}", operationContent));
                        }
                        break;
                    case "左键拖动":
                        // 解析起始坐标、拖动时长和结束坐标 (x1,y1;拖动时长毫秒数;x2,y2)
                        if (!string.IsNullOrEmpty(operationContent) && operationContent.Contains(";"))
                        {
                            string[] segments = operationContent.Split(';');
                            if (segments.Length == 3)
                            {
                                string[] startParts = segments[0].Split(',');
                                string durationStr = segments[1].Trim();
                                string[] endParts = segments[2].Split(',');
                                
                                if (startParts.Length == 2 && endParts.Length == 2 &&
                                    int.TryParse(startParts[0].Trim(), out int startX) && 
                                    int.TryParse(startParts[1].Trim(), out int startY) &&
                                    int.TryParse(durationStr, out int duration) &&
                                    int.TryParse(endParts[0].Trim(), out int endX) && 
                                    int.TryParse(endParts[1].Trim(), out int endY))
                                {
                                    HelperFunctions.MouseLeftDrag(startX, startY, endX, endY, duration);
                                }
                                else
                                {
                                    throw new ArgumentException(string.Format("无效的坐标或时长格式: {0}", operationContent));
                                }
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("无效的拖动格式: {0}", operationContent));
                            }
                        }
                        else
                        {
                            throw new ArgumentException(string.Format("拖动操作格式不正确: {0}", operationContent));
                        }
                        break;
                    case "鼠标滚轮":
                        // 解析滚轮值
                        if (!string.IsNullOrEmpty(operationContent) && 
                            int.TryParse(operationContent.Trim(), out int delta))
                        {
                            HelperFunctions.MouseWheel(delta);
                        }
                        else
                        {
                            throw new ArgumentException(string.Format("无效的滚轮值: {0}", operationContent));
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("执行鼠标操作 '{0}' 时发生错误: {1}", operationType, ex.Message));
            }
        }
        
        // 执行键盘操作
        private void ExecuteKeyboardOperation(string operationType, string operationContent)
        {
            try
            {
                switch (operationType)
                {
                    case "单击按键":
                        if (!string.IsNullOrEmpty(operationContent))
                        {
                            HelperFunctions.KeyboardKeyPress(operationContent);
                        }
                        else
                        {
                            throw new ArgumentException("按键内容不能为空");
                        }
                        break;
                    case "按下按键":
                        if (!string.IsNullOrEmpty(operationContent))
                        {
                            HelperFunctions.KeyboardKeyDown(operationContent);
                        }
                        else
                        {
                            throw new ArgumentException("按键内容不能为空");
                        }
                        break;
                    case "释放按键":
                        if (!string.IsNullOrEmpty(operationContent))
                        {
                            HelperFunctions.KeyboardKeyUp(operationContent);
                        }
                        else
                        {
                            throw new ArgumentException("按键内容不能为空");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("执行键盘操作 '{0}' 时发生错误: {1}", operationType, ex.Message));
            }
        }
        
        // 查找循环结束位置
        private int FindLoopEndIndex(List<DataGridViewRow> rows, int startIndex)
        {
            // 使用栈来处理嵌套循环
            Stack<int> loopStack = new Stack<int>();
            
            // 从开始位置的下一行开始查找
            for (int i = startIndex + 1; i < rows.Count; i++)
            {
                DataGridViewRow row = rows[i];
                
                // 获取设备类型和操作类型
                string deviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString();
                string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                
                // 检查是否是循环操作
                if (deviceType == "循环")
                {
                    if (operationType == "开始")
                    {
                        // 遇到嵌套的循环开始，压入栈中
                        loopStack.Push(i);
                    }
                    else if (operationType == "结束")
                    {
                        // 遇到循环结束
                        if (loopStack.Count == 0)
                        {
                            // 这是我们要找的循环结束位置
                            return i;
                        }
                        else
                        {
                            // 弹出匹配的嵌套循环开始
                            loopStack.Pop();
                        }
                    }
                }
            }
            
            // 未找到匹配的循环结束
            return -1;
        }
        
        // 执行循环体
        private void ExecuteLoop(List<DataGridViewRow> rows, int loopStartIndex, int loopEndIndex, int loopCount, int currentLevel = 1)
        {
            // 检查边界条件
            if (loopStartIndex > loopEndIndex || loopStartIndex < 0 || loopEndIndex >= rows.Count)
                return;
            
            // 检查无限循环限制：无限循环只能在最外层使用
            bool isInfinityLoop = (loopCount == -1);
            if (isInfinityLoop && currentLevel > 1)
            {
                MessageBox.Show("错误：无限循环只能在最外层使用，内层循环不能使用无限循环。", "循环执行错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                isProgramRunning = false;
                return;
            }
            
            // 循环执行
            int currentLoopCount = 0;
            while (isProgramRunning && (isInfinityLoop || currentLoopCount < loopCount))
            {
                // 遍历循环体内的每一行
                for (int i = loopStartIndex; i <= loopEndIndex && isProgramRunning; i++)
                {
                    DataGridViewRow row = rows[i];
                    
                    // 高亮显示当前执行的行
                    HighlightRow(row.Index);
                    
                    // 获取设备类型、操作类型和操作内容
                    string deviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString();
                    string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                    string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString();
                    
                    // 处理嵌套循环
                    if (deviceType == "循环")
                    {
                        if (operationType == "开始")
                        {
                            // 查找嵌套循环的结束位置
                            int nestedLoopEndIndex = FindLoopEndIndex(rows, i);
                            if (nestedLoopEndIndex != -1)
                            {
                                // 获取嵌套循环次数
                                int nestedLoopCount = -1; // -1 表示无限循环
                                if (!string.IsNullOrEmpty(operationContent) && 
                                    int.TryParse(operationContent.Trim(), out int count) && count > 0)
                                {
                                    nestedLoopCount = count;
                                }
                                
                                // 执行嵌套循环（层级加1）
                                ExecuteLoop(rows, i + 1, nestedLoopEndIndex - 1, nestedLoopCount, currentLevel + 1);
                                
                                // 跳过嵌套循环体
                                i = nestedLoopEndIndex;
                            }
                        }
                        // 循环结束操作不需要特殊处理
                        continue;
                    }
                    
                    // 根据设备类型和操作类型执行相应的操作
                    switch (deviceType)
                    {
                        case "鼠标":
                            ExecuteMouseOperation(operationType, operationContent);
                            break;
                        case "键盘":
                            ExecuteKeyboardOperation(operationType, operationContent);
                            break;
                        case "延时":
                            ExecuteDelayOperation(operationContent);
                            break;
                    }
                    
                    // 检查程序是否仍在运行状态
                    if (!isProgramRunning)
                        break;
                }
                
                // 增加循环计数
                currentLoopCount++;
                
                // 检查程序是否仍在运行状态
                if (!isProgramRunning)
                    break;
            }
        }
        
        // 执行延时操作
        private void ExecuteDelayOperation(string operationContent)
        {
            try
            {
                // 解析延时毫秒数
                if (!string.IsNullOrEmpty(operationContent) && 
                    int.TryParse(operationContent.Trim(), out int milliseconds))
                {
                    // 将延时分解为多个短延时（每次100毫秒），以便更好地响应停止信号
                    const int chunkSize = 100; // 每个时间片的毫秒数
                    int remainingMilliseconds = milliseconds;
                    
                    while (remainingMilliseconds > 0 && isProgramRunning)
                    {
                        // 计算当前时间片的延时长度
                        int currentChunk = Math.Min(chunkSize, remainingMilliseconds);
                        
                        // 执行当前时间片的延时
                        DateTime start = DateTime.Now;
                        while ((DateTime.Now - start).TotalMilliseconds < currentChunk && isProgramRunning)
                        {
                            Application.DoEvents();
                            System.Threading.Thread.Sleep(10); // 短暂休眠以减少CPU占用
                        }
                        
                        // 减去已执行的时间
                        remainingMilliseconds -= currentChunk;
                        
                        // 在每个时间片结束后再次检查程序运行状态
                        if (!isProgramRunning)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    throw new ArgumentException(string.Format("无效的延时值: {0}", operationContent));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("执行延时操作时发生错误: {0}", ex.Message));
            }
        }
        
        // 帮助按钮点击事件
        private void buttonHelp_Click(object sender, EventArgs e)
        {
            string helpText = "使用说明：\n\n" +
                             "1. 在表格中添加操作行\n" +
                             "2. 选择设备类型（鼠标、键盘、延时、循环）\n" +
                             "3. 根据设备类型选择相应的操作类型并填写内容：\n\n" +
                             "【鼠标操作】\n" +
                             "   - 移动鼠标：x,y 坐标（例如：100,200）\n" +
                             "   - 点击鼠标左键：x,y 坐标（例如：100,200）\n" +
                             "   - 点击鼠标右键：x,y 坐标（例如：100,200）\n" +
                             "   - 双击鼠标左键：x,y 坐标（例如：100,200）\n" +
                             "   - 滚动鼠标滚轮：滚动值（正数向上滚动，负数向下滚动，单位：1表示向上滚动一下）\n\n" +
                             "【键盘操作】\n" +
                             "   - 按键：按键名称（例如：A, Ctrl+C, Alt+F4, F1）\n" +
                             "   - 按下按键：按下某个按键不释放（例如：Ctrl）\n" +
                             "   - 释放按键：释放之前按下的按键（例如：Ctrl）\n\n" +
                             "【延时操作】\n" +
                             "   - 延时：延时时间（单位：毫秒，例如：1000表示延时1秒）\n\n" +
                             "【循环操作】\n" +
                             "   - 开始：循环开始标记，可指定循环次数（留空表示无限循环，仅最外层可用）\n" +
                             "   - 结束：循环结束标记\n\n" +
                             "4. 使用\"选择坐标或按键\"按钮快速获取鼠标坐标或按键信息\n" +
                             "5. 勾选操作行前面的复选框来选择要执行的操作\n" +
                             "6. 设置开始和退出热键（在\"设置开始热键\"和\"设置退出热键\"按钮中设置）\n" +
                             "7. 点击\"开始执行\"按钮或按下开始热键执行操作序列\n" +
                             "8. 在执行过程中可随时按下退出热键停止执行\n";

            MessageBox.Show(helpText, "帮助", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            // 重置鼠标光标，避免保持问号状态
            this.Cursor = Cursors.Default;
        }

        // 当前主题索引，用于循环切换主题
        private int currentThemeIndex = 0;
        
        private void buttonTheme_Click(object sender, EventArgs e)
        {
            // 获取所有内置主题
            BuiltInTheme[] themes = (BuiltInTheme[])Enum.GetValues(typeof(BuiltInTheme));
            
            // 循环切换到下一个主题
            currentThemeIndex = (currentThemeIndex + 1) % themes.Length;
            
            // 应用新主题
            SwitchTheme(themes[currentThemeIndex]);
        }
        
        // 重载SwitchTheme方法，支持内置主题
        public void SwitchTheme(BuiltInTheme builtInTheme)
        {
            themeManager = new ThemeManager(builtInTheme);
            themeManager.ApplyTheme(this);
            
            // 重新应用DataGridView样式
            if (dataGridViewManager != null)
            {
                // 触发一次数据刷新以确保样式正确应用
                dataGridViewOperationList.Refresh();
            }
        }

        // 获取当前行的操作类型
        private string GetCurrentOperationType(int rowIndex)
        {
            if (rowIndex >= 0 && rowIndex < dataGridViewOperationList.Rows.Count)
            {
                var cell = dataGridViewOperationList.Rows[rowIndex].Cells["OperationType"];
                return cell?.Value?.ToString();
            }
            return null;
        }
        
        // 获取需要被执行的行
        private List<DataGridViewRow> GetExecuteRows()
        {
            List<DataGridViewRow> executeRows = new List<DataGridViewRow>();
            
            // 遍历所有行，筛选出"选择"列被勾选的行
            foreach (DataGridViewRow row in dataGridViewOperationList.Rows)
            {
                // 检查行是否有效（不是新行）
                if (!row.IsNewRow)
                {
                    // 获取"选择"列的单元格
                    DataGridViewCell checkCell = row.Cells["CheckStatus"];
                    
                    // 检查单元格值是否为true（被选中）
                    if (checkCell != null && checkCell.Value != null && 
                        bool.TryParse(checkCell.Value.ToString(), out bool isChecked) && isChecked)
                    {
                        executeRows.Add(row);
                    }
                }
            }
            executeRows = CheckOperationContent(executeRows);
            executeRows = CheckLogic(executeRows);
            return executeRows;
        }
        
        private List<DataGridViewRow> CheckOperationContent(List<DataGridViewRow> executeRows)
        {
            List<DataGridViewRow> validRows = new List<DataGridViewRow>();
            errorRows.Clear(); // 清空之前的错误行记录
            
            foreach (DataGridViewRow row in executeRows)
            {
                string deviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString();
                string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString();
                
                bool isValid = true;
                
                // 根据设备类型和操作类型验证操作内容格式
                switch (deviceType)
                {
                    case "鼠标":
                        switch (operationType)
                        {
                            case "移动到坐标":
                            case "左键单击":
                            case "左键双击":
                            case "右键单击":
                            case "右键双击":
                            case "中键单击":
                                // 验证坐标格式 (x,y)
                                if (!string.IsNullOrEmpty(operationContent))
                                {
                                    var parts = operationContent.Split(',');
                                    if (parts.Length != 2 || 
                                        !int.TryParse(parts[0].Trim(), out _) || 
                                        !int.TryParse(parts[1].Trim(), out _))
                                    {
                                        isValid = false;
                                    }
                                }
                                break;
                            case "左键拖动":
                                // 验证拖动格式 (x1,y1;拖动时长毫秒数;x2,y2)
                                if (!string.IsNullOrEmpty(operationContent))
                                {
                                    var segments = operationContent.Split(';');
                                    if (segments.Length != 3 ||
                                        !HelperFunctions.ValidateCoordinate(segments[0]) ||
                                        !int.TryParse(segments[1].Trim(), out _) ||
                                        !HelperFunctions.ValidateCoordinate(segments[2]))
                                    {
                                        isValid = false;
                                    }
                                }
                                break;
                            case "鼠标滚轮":
                                // 验证滚轮值是否是整数
                                if (!string.IsNullOrEmpty(operationContent) && 
                                    !int.TryParse(operationContent.Trim(), out _))
                                {
                                    isValid = false;
                                }
                                break;
                        }
                        break;
                    case "键盘":
                        switch (operationType)
                        {
                            case "单击按键":
                            case "按下按键":
                            case "释放按键":
                                // 验证按键内容是否有效
                                if (!string.IsNullOrEmpty(operationContent) && 
                                    !InputValidator.ValidateOperationContent(operationType, operationContent))
                                {
                                    isValid = false;
                                }
                                break;
                        }
                        break;
                    case "延时":
                        // 验证延时值是否是正整数
                        if (!string.IsNullOrEmpty(operationContent) && 
                            (!int.TryParse(operationContent.Trim(), out int delayValue) || delayValue <= 0))
                        {
                            isValid = false;
                        }
                        break;
                    case "循环":
                        switch (operationType)
                        {
                            case "开始":
                                // 循环次数必须是正整数或空（表示无限循环）
                                if (!string.IsNullOrEmpty(operationContent) && 
                                    (!int.TryParse(operationContent.Trim(), out int loopCount) || loopCount <= 0))
                                {
                                    isValid = false;
                                }
                                break;
                        }
                        break;
                }
                
                // 如果验证失败，记录错误行
                if (!isValid)
                {
                    errorRows.Add(row.Index);
                }
                else
                {
                    validRows.Add(row);
                }
            }
            
            // 如果有错误行，显示错误信息
            if (errorRows.Count > 0)
            {
                string errorMsg = "以下行的操作内容格式不正确：\n";
                foreach (int rowIndex in errorRows)
                {
                    errorMsg += $"第 {rowIndex + 1} 行\n";
                }
                errorMsg += "\n请检查操作内容格式是否正确。";
                MessageBox.Show(errorMsg, "操作内容验证错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return new List<DataGridViewRow>(); // 返回空列表阻止执行
            }
            
            return validRows;
        }

        private List<DataGridViewRow> CheckLogic(List<DataGridViewRow> executeRows)
        {
            // 检查循环开始结束是否配对及顺序是否正确
            Stack<int> loopStack = new Stack<int>(); // 用于跟踪循环开始的位置
            errorRows.Clear(); // 清空之前的错误行记录
            // 记录是否有无限循环
            bool hasInfinityLoop = false;
            
            for (int i = 0; i < executeRows.Count; i++)
            {
                DataGridViewRow row = executeRows[i];
                
                // 获取设备类型和操作类型
                string deviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString();
                string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString();
                
                // 检查是否是循环操作
                if (deviceType == "循环")
                {
                    if (operationType == "开始")
                    {
                        // 检查是否是无限循环
                        bool isCurrentInfinityLoop = string.IsNullOrWhiteSpace(operationContent);
                        
                        // 检查无限循环规则：无限循环只能在最外层使用
                        if (isCurrentInfinityLoop)
                        {
                            // 当前层级是loopStack.Count + 1（因为即将压入栈）
                            int currentLevel = loopStack.Count + 1;
                            
                            // 如果已经存在无限循环，或者当前不是最外层（层级>1），则报错
                            if (hasInfinityLoop || currentLevel > 1)
                            {
                                errorRows.Add(i);
                            }
                            else
                            {
                                hasInfinityLoop = true;
                            }
                        }
                        
                        // 遇到循环开始，将其位置压入栈中
                        loopStack.Push(i);
                    }
                    else if (operationType == "结束")
                    {
                        // 遇到循环结束，检查是否有匹配的开始
                        if (loopStack.Count == 0)
                        {
                            // 没有匹配的开始，记录错误
                            errorRows.Add(i);
                        }
                        else
                        {
                            // 弹出匹配的开始位置
                            loopStack.Pop();
                        }
                    }
                }
            }
            
            // 检查是否有未闭合的循环开始
            while (loopStack.Count > 0)
            {
                int unClosedLoopIndex = loopStack.Pop();
                errorRows.Add(unClosedLoopIndex);
            }
            
            // 如果有错误，显示错误信息并返回空列表
            if (errorRows.Count > 0)
            {
                // 构建错误信息
                string errorMsg = "循环操作配对错误：\n";
                foreach (int rowIndex in errorRows)
                {
                    DataGridViewRow row = executeRows[rowIndex];
                    string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString();
                    string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString();
                    
                    if (string.IsNullOrWhiteSpace(operationContent))
                    {
                        errorMsg += $"第 {row.Index + 1} 行: 无限循环只能在最外层使用，内层循环不能使用无限循环\n";
                    }
                    else
                    {
                        errorMsg += $"第 {row.Index + 1} 行: 循环{operationType} 缺少配对\n";
                    }
                }
                
                MessageBox.Show(errorMsg, "逻辑检查错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return new List<DataGridViewRow>(); // 返回空列表，阻止执行
            }
            
            return executeRows;
        }
        
        // 键盘钩子按键事件处理
        private void KeyboardHookManager_KeyPressed(object sender, KeyEventArgs e)
        {
            // 检查是否按下了开始程序运行的快捷键
            if (!isProgramRunning)
            {
                if (IsStartHotKeyPressed(e))
                {
                    // 开始执行任务列表
                    ExecuteTaskList();
                    return;
                }
            }
            // 只有在程序正在运行时，才检查退出快捷键
            else if (isProgramRunning)
            {
                // 检查是否按下了退出程序运行的快捷键
                if (IsExitHotKeyPressed(e))
                {
                    // 退出程序运行状态
                    StopProgramExecution();
                    return;
                }
            }
            
            // 检查是否正在捕获鼠标坐标
            if (isCapturingMousePosition)
            {
                // 检查是(确认坐标)
                if (e.PressedKeys.Contains(okHotKey1) && e.KeyName == okHotKey2)
                {
                    // 获取当前鼠标坐标
                    Point mousePosition = Cursor.Position;
                    
                    // 将坐标填入当前单元格
                    if (lastFocusedRow >= 0 && lastFocusedColumn >= 0)
                    {
                        var cell = dataGridViewOperationList.Rows[lastFocusedRow].Cells[lastFocusedColumn];
                        if (cell.Value != null)
                        {
                            cell.Value += $"{mousePosition.X},{mousePosition.Y}";
                        }
                        else
                        {
                            cell.Value = $"{mousePosition.X},{mousePosition.Y}";
                        }
                    }
                    
                    // 停止捕获
                    isCapturingMousePosition = false;
                    
                    // 恢复窗体
                    this.WindowState = FormWindowState.Normal;
                }
                // 检查是否(取消选择)
                else if (e.PressedKeys.Contains(cancelHotKey2) && e.KeyName == cancelHotKey2)
                {
                    // 停止捕获
                    isCapturingMousePosition = false;
                    
                    // 恢复窗体
                    this.WindowState = FormWindowState.Normal;
                }
            }
            // 检查是否正在捕获键盘输入
            else if (isCapturingKeyboardInput)
            {
                // 清空之前捕获的按键
                capturedKeys.Clear();
                
                // 添加当前按下的所有按键
                foreach (string key in e.PressedKeys)
                {
                    // 特殊处理修饰键
                    if (key == "Ctrl" || key == "Alt" || key == "Shift")
                    {
                        capturedKeys.Add(key);
                    }
                }
                
                // 添加当前按下的主键（非修饰键）
                if (e.KeyName != "Ctrl" && e.KeyName != "Alt" && e.KeyName != "Shift")
                {
                    capturedKeys.Add(e.KeyName);
                }
                
                // 如果有按键被按下，则记录并填入单元格
                if (capturedKeys.Count > 0)
                {
                    // 构造按键组合字符串
                    string keyCombination = "";
                    if (capturedKeys.Count == 1)
                    {
                        // 单个按键
                        keyCombination = capturedKeys[0];
                    }
                    else if (capturedKeys.Count >= 2)
                    {
                        // 组合键（修饰键+主键）
                        string modifier = "";
                        string mainKey = "";
                        
                        // 查找修饰键和主键
                        foreach (string key in capturedKeys)
                        {
                            if (key == "Ctrl" || key == "Alt" || key == "Shift")
                            {
                                modifier = key;
                            }
                            else
                            {
                                mainKey = key;
                            }
                        }
                        
                        // 构造组合键字符串
                        if (!string.IsNullOrEmpty(modifier) && !string.IsNullOrEmpty(mainKey))
                        {
                            keyCombination = $"{modifier}+{mainKey}";
                        }
                        else if (!string.IsNullOrEmpty(mainKey))
                        {
                            keyCombination = mainKey;
                        }
                        else
                        {
                            keyCombination = capturedKeys[0];
                        }
                    }
                    
                    // 将按键组合填入当前单元格
                    if (lastFocusedRow >= 0 && lastFocusedColumn >= 0)
                    {
                        dataGridViewOperationList.Rows[lastFocusedRow].Cells[lastFocusedColumn].Value = keyCombination;
                    }
                    
                    // 停止捕获
                    isCapturingKeyboardInput = false;
                    
                    // 显示成功消息
                    MessageBox.Show($"已成功记录按键组合: {keyCombination}", "按键记录", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private string okHotKey1 = "Ctrl";
        private string okHotKey2 = "F11";
        private string cancelHotKey1 = "Ctrl";
        private string cancelHotKey2 = "F12";

        // 设置坐标或按键按钮点击事件
        private void buttonSetPositionOrKey_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的单元格
            if (dataGridViewOperationList.CurrentCell != null)
            {
                int rowIndex = dataGridViewOperationList.CurrentCell.RowIndex;
                int columnIndex = dataGridViewOperationList.CurrentCell.ColumnIndex;
                
                // 检查是否是操作内容列
                if (dataGridViewOperationList.Columns[columnIndex].Name == "OperationContent")
                {
                    // 记录当前单元格位置
                    lastFocusedRow = rowIndex;
                    lastFocusedColumn = columnIndex;
                    
                    // 获取当前行的操作类型
                    string operationType = GetCurrentOperationType(rowIndex);
                    
                    // 根据操作类型执行不同的操作
                    switch (operationType)
                    {
                        case "移动到坐标":
                        case "左键单击":
                        case "左键双击":
                        case "右键单击":
                        case "右键双击":
                        case "中键单击":
                        case "左键拖动":
                            // 显示坐标采集对话框（除非用户选择不再显示）
                            if (!dontShowMouseCaptureDialog)
                            {
                                MousePositionCaptureDialog dialog = new MousePositionCaptureDialog($"{okHotKey1}+{okHotKey2}", $"{cancelHotKey1}+{cancelHotKey2}");
                                if (dialog.ShowDialog() == DialogResult.OK)
                                {
                                    // 记录用户的选择
                                    dontShowMouseCaptureDialog = dialog.DontShowAgain;
                                }
                            }
                            
                            // 开始捕获鼠标坐标
                            isCapturingMousePosition = true;
                            
                            // 最小化窗体
                            this.WindowState = FormWindowState.Minimized;
                            break;
                            
                        case "单击按键":
                            // 显示按键记录对话框
                            using (KeyCaptureDialog keyCaptureDialog = new KeyCaptureDialog())
                            {
                                if (keyCaptureDialog.ShowDialog() == DialogResult.OK)
                                {
                                    // 将捕获到的按键组合填入当前单元格
                                    if (lastFocusedRow >= 0 && lastFocusedColumn >= 0)
                                    {
                                        dataGridViewOperationList.Rows[lastFocusedRow].Cells[lastFocusedColumn].Value = keyCaptureDialog.CapturedKeyCombination;
                                    }
                                }
                            }
                            break;
                            
                        default:
                            MessageBox.Show("请先选择操作类型。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            break;
                    }
                }
                else
                {
                    MessageBox.Show("请选择操作内容列中的单元格。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请先选择一个单元格。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void buttonSetStartRunHotKey_Click(object sender, EventArgs e)
        {
            // 显示按键捕获对话框
            using (KeyCaptureDialog keyCaptureDialog = new KeyCaptureDialog())
            {
                if (keyCaptureDialog.ShowDialog() == DialogResult.OK)
                {
                    // 保存捕获到的按键组合作为退出程序运行的快捷键
                    startHotKey = keyCaptureDialog.CapturedKeyCombination;

                    // 更新标题栏显示
                    UpdateTitleWithStartAndExitKey();

                    // 显示成功消息
                    MessageBox.Show($"已设置开始运行的快捷键为: {keyCaptureDialog.CapturedKeyCombination}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        // 开始执行按钮点击事件
        private void buttonStartRun_Click(object sender, EventArgs e)
        {
            // 检查程序是否正在运行
            if (isProgramRunning)
            {
                // 如果正在运行，则停止执行
                StopProgramExecution();
            }
            else
            {
                // 如果未运行，则开始执行任务列表
                ExecuteTaskList();
            }
        }

        // 判断是否按下了开始快捷键
        private bool IsStartHotKeyPressed(KeyEventArgs e)
        {
            // 检查是否是单个按键
            if (e.PressedKeys.Count == 1)
            {
                return startHotKey == e.KeyName;
            }
            
            // 检查组合键
            if (e.PressedKeys.Count >= 2)
            {
                // 构造组合键字符串进行比较
                string pressedCombination = "";
                if (e.PressedKeys.Count == 2)
                {
                    // 修饰键+主键格式
                    string modifier = "";
                    string mainKey = "";
                    
                    foreach (string key in e.PressedKeys)
                    {
                        if (key == "Ctrl" || key == "Alt" || key == "Shift")
                        {
                            modifier = key;
                        }
                        else
                        {
                            mainKey = key;
                        }
                    }
                    
                    if (!string.IsNullOrEmpty(modifier) && !string.IsNullOrEmpty(mainKey))
                    {
                        pressedCombination = $"{modifier}+{mainKey}";
                    }
                }
                
                return pressedCombination == startHotKey;
            }
            
            return false;
        }
        
        // 判断是否按下了退出快捷键
        private bool IsExitHotKeyPressed(KeyEventArgs e)
        {
            // 检查是否是单个按键
            if (e.PressedKeys.Count == 1)
            {
                return exitHotKey == e.KeyName;
            }
            
            // 检查组合键
            if (e.PressedKeys.Count >= 2)
            {
                // 构造组合键字符串进行比较
                string pressedCombination = "";
                if (e.PressedKeys.Count == 2)
                {
                    // 修饰键+主键格式
                    string modifier = "";
                    string mainKey = "";
                    
                    foreach (string key in e.PressedKeys)
                    {
                        if (key == "Ctrl" || key == "Alt" || key == "Shift")
                        {
                            modifier = key;
                        }
                        else
                        {
                            mainKey = key;
                        }
                    }
                    
                    if (!string.IsNullOrEmpty(modifier) && !string.IsNullOrEmpty(mainKey))
                    {
                        pressedCombination = $"{modifier}+{mainKey}";
                    }
                }
                
                return pressedCombination == exitHotKey;
            }
            
            return false;
        }
        
        private void buttonSetExitRunHotKey_Click(object sender, EventArgs e)
        {
            // 显示按键捕获对话框
            using (KeyCaptureDialog keyCaptureDialog = new KeyCaptureDialog())
            {
                if (keyCaptureDialog.ShowDialog() == DialogResult.OK)
                {
                    // 保存捕获到的按键组合作为退出程序运行的快捷键
                    exitHotKey = keyCaptureDialog.CapturedKeyCombination;
                    
                    // 更新标题栏显示
                    UpdateTitleWithStartAndExitKey();
                    
                    // 显示成功消息
                    MessageBox.Show($"已设置退出运行的快捷键为: {keyCaptureDialog.CapturedKeyCombination}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        // 更新标题栏显示退出快捷键
        private void UpdateTitleWithStartAndExitKey()
        {
            this.Text = $"鼠标键盘操作模拟器 - 快捷键（开始：{startHotKey}，退出：{exitHotKey}）";
        }

        private void buttonExportConfiguration_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建保存文件对话框
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "JSON文件|*.json|所有文件|*.*";
                saveFileDialog.Title = "导出配置";
                saveFileDialog.DefaultExt = "json";
                
                // 如果用户点击了保存按钮
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 创建配置对象
                    Configuration config = new Configuration();
                    
                    // 设置快捷键信息
                    config.StartHotKey = startHotKey;
                    config.ExitHotKey = exitHotKey;
                    
                    // 初始化屏幕信息
                    string screenInfo = ScreenInfo.GetScreenInfoString();
                    
                    // 遍历DataGridView中的所有行，查找坐标操作以确定正确的屏幕信息
                    foreach (DataGridViewRow row in dataGridViewOperationList.Rows)
                    {
                        // 跳过新行（通常是最后一行）
                        if (row.IsNewRow)
                            continue;
                        
                        string operationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString() ?? "";
                        string operationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString() ?? "";
                        
                        // 如果是坐标操作，根据坐标确定屏幕信息
                        if (IsCoordinateOperation("鼠标", operationType) && !string.IsNullOrEmpty(operationContent))
                        {
                            // 解析操作内容中的坐标
                            if (TryParseOperationCoordinates(operationType, operationContent, out int x, out int y))
                            {
                                // 根据鼠标坐标获取对应的屏幕信息
                                screenInfo = ScreenInfo.GetScreenInfoAtMousePosition(x, y);
                                break; // 找到第一个坐标操作就足够了
                            }
                        }
                    }
                    
                    // 记录导出时的屏幕信息（分辨率和DPI缩放因子）
                    config.ScreenInfo = screenInfo;
                    
                    // 遍历DataGridView中的所有行
                    foreach (DataGridViewRow row in dataGridViewOperationList.Rows)
                    {
                        // 跳过新行（通常是最后一行）
                        if (row.IsNewRow)
                            continue;
                        
                        // 创建操作列表项
                        OperationListItem item = new OperationListItem();
                        
                        // 获取各列的值
                        item.CheckStatus = Convert.ToBoolean(dataGridViewManager.GetCellValue(row.Index, "CheckStatus") ?? false);
                        item.Index = row.Index + 1; // 使用1基索引
                        
                        item.DeviceType = dataGridViewManager.GetCellValue(row.Index, "DeviceType")?.ToString() ?? "";
                        item.OperationType = dataGridViewManager.GetCellValue(row.Index, "OperationType")?.ToString() ?? "";
                        item.OperationContent = dataGridViewManager.GetCellValue(row.Index, "OperationContent")?.ToString() ?? "";
                        
                        // 添加到列表中
                        config.OperationList.Add(item);
                    }
                    
                    // 序列化为JSON
                    string jsonString = JsonConvert.SerializeObject(config, Formatting.Indented);
                    
                    // 写入文件
                    File.WriteAllText(saveFileDialog.FileName, jsonString);
                    
                    // 显示成功消息
                    MessageBox.Show($"配置已成功导出到:\n{saveFileDialog.FileName}", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                // 显示错误消息
                MessageBox.Show($"导出配置时发生错误:\n{ex.Message}", "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonImportConfiguration_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建打开文件对话框
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "JSON文件|*.json|所有文件|*.*";
                openFileDialog.Title = "导入配置";
                openFileDialog.DefaultExt = "json";
                
                // 如果用户点击了打开按钮
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 读取文件内容
                    string jsonString = File.ReadAllText(openFileDialog.FileName);
                    
                    // 尝试反序列化为配置对象（新格式）
                    
                    Configuration config = JsonConvert.DeserializeObject<Configuration>(jsonString);
                    
                    // 更新快捷键信息
                    startHotKey = config.StartHotKey;
                    exitHotKey = config.ExitHotKey;
                    
                    // 更新标题栏显示
                    UpdateTitleWithStartAndExitKey();
                    
                    // 获取当前屏幕信息
                    string currentScreenInfo = ScreenInfo.GetScreenInfoString();
                    
                    // 检查是否需要重新计算坐标（如果屏幕信息不同）
                    bool needRecalculate = !string.IsNullOrEmpty(config.ScreenInfo) && config.ScreenInfo != currentScreenInfo;
                    
                    // 清空现有的操作列表
                    dataGridViewOperationList.Rows.Clear();
                    
                    // 遍历导入的操作列表项
                    foreach (OperationListItem item in config.OperationList)
                    {
                        // 添加新行
                        int rowIndex = dataGridViewOperationList.Rows.Add();
                        
                        // 设置各列的值
                        dataGridViewOperationList.Rows[rowIndex].Cells["CheckStatus"].Value = item.CheckStatus;
                        dataGridViewOperationList.Rows[rowIndex].Cells["Index"].Value = item.Index;
                        dataGridViewOperationList.Rows[rowIndex].Cells["DeviceType"].Value = item.DeviceType;
                        dataGridViewOperationList.Rows[rowIndex].Cells["OperationType"].Value = item.OperationType;
                        
                        // 如果需要重新计算坐标且操作内容是坐标，则进行转换
                        string operationContent = item.OperationContent;
                        if (needRecalculate && IsCoordinateOperation(item.DeviceType, item.OperationType))
                        {
                            operationContent = ScreenInfo.RecalculateCoordinate(operationContent, config.ScreenInfo, currentScreenInfo);
                        }
                        
                        dataGridViewOperationList.Rows[rowIndex].Cells["OperationContent"].Value = operationContent;
                    }
                    
                    // 更新行号
                    dataGridViewManager.UpdateRowNumbers();
                    
                    // 显示成功消息
                    string message = $"配置已成功从以下文件导入:\n{openFileDialog.FileName}";
                    if (needRecalculate)
                    {
                        message += "\n\n注意：由于屏幕分辨率或DPI发生变化，坐标已自动调整。";
                    }
                    MessageBox.Show(message, "导入成功", MessageBoxButtons.OK, MessageBoxIcon.Information);                
                }
            }
            catch (Exception ex)
            {
                // 显示错误消息
                MessageBox.Show($"导入配置时发生错误:\n{ex.Message}", "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 判断是否是涉及坐标的操作
        private bool IsCoordinateOperation(string deviceType, string operationType)
        {
            // 鼠标移动操作
            if (deviceType == "鼠标")
            {
                if (operationType == "鼠标滚轮")
                    return false;
                return true;
            }
            return false;
        }

        // 解析操作内容中的坐标
        private bool TryParseOperationCoordinates(string operationType, string operationContent, out int x, out int y)
        {
            x = 0;
            y = 0;
            
            if (string.IsNullOrEmpty(operationContent))
                return false;
            
            // 处理不同类型的坐标操作
            if (operationType == "左键拖动")
            {
                // 拖动操作格式: 起始坐标;拖动时长毫秒数;结束坐标
                string[] segments = operationContent.Split(';');
                if (segments.Length >= 1)
                {
                    // 解析起始坐标
                    string[] startParts = segments[0].Split(',');
                    if (startParts.Length >= 2 && int.TryParse(startParts[0], out x) && int.TryParse(startParts[1], out y))
                    {
                        return true;
                    }
                }
            }
            else
            {
                // 其他坐标操作格式: x,y
                string[] parts = operationContent.Split(',');
                if (parts.Length >= 2 && int.TryParse(parts[0], out x) && int.TryParse(parts[1], out y))
                {
                    return true;
                }
            }
            
            return false;
        }



    } // classMouseKeyboardOperationSimulator
} // namespace MouseKeyboardOperationSimulator